package com.oscar.ehome.view.loginview;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.ShapeDrawable;
import android.os.Bundle;
import android.os.Environment;
import android.util.Base64;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.oscar.ehome.MainActivity;
import com.oscar.ehome.R;
import com.oscar.ehome.base.AppManager;
import com.oscar.ehome.base.activity.BasesActivity;
import com.oscar.ehome.bean.loginbean.idcardbean.CardInfoBean;
import com.oscar.ehome.bean.loginbean.idcardbean.ComitMessageBean;
import com.oscar.ehome.bean.loginbean.idcardbean.IdBean;
import com.oscar.ehome.bean.loginbean.idcardbean.IdCardBean;
import com.oscar.ehome.bean.loginbean.idcardbean.ItemBean;
import com.oscar.ehome.bean.loginbean.idcardbean.MessageBean;
import com.oscar.ehome.bean.setbean.FeedBackBean;
import com.oscar.ehome.bean.setbean.TokenBean;
import com.oscar.ehome.bean.teamBean.TeamListBean;
import com.oscar.ehome.bean.teamBean.UserAppInfoBean;
import com.oscar.ehome.bean.teamBean.UserRoleStaticBean;
import com.oscar.ehome.bean.teamBean.UserStartStaticBean;
import com.oscar.ehome.presenter.BasePresenter;
import com.oscar.ehome.presenter.SetPresenter;
import com.oscar.ehome.presenter.SubcomitPresenter;
import com.oscar.ehome.presenter.TeamPresenter;
import com.oscar.ehome.provider.zxing.client.android.result.IdCardIdentify;
import com.oscar.ehome.utils.basethem.TintManager;
import com.oscar.ehome.utils.imageview.ChuliPhoto;
import com.oscar.ehome.utils.selfdialog.CustomBackDialog;
import com.oscar.ehome.utils.system.SystemConfigFactory;
import com.oscar.ehome.utils.util.AesUtils;
import com.oscar.ehome.utils.util.CommonUtils;
import com.oscar.ehome.utils.util.ToastUtil;
import com.oscar.ehome.utils.util.makeTime;
import com.oscar.ehome.utils.view.MyImageView;
import com.oscar.ehome.view.loginview.view.ApporveView;
import com.oscar.ehome.view.loginview.view.SubcomitMessageView;
import com.oscar.ehome.view.setview.view.FeedBackView;
import com.oscar.ehome.view.teamview.TeamDetailActivity;
import com.oscar.ehome.view.teamview.view.MessageInfoView;
import com.oscar.ehome.view.teamview.view.TeamListView;
import com.qiniu.android.http.ResponseInfo;
import com.qiniu.android.storage.UpCompletionHandler;
import com.qiniu.android.storage.UploadManager;

import org.json.JSONObject;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by 孟婉和 on 2017/6/22.
 */

public class SubmitActivity extends BasesActivity implements SubcomitMessageView, FeedBackView, MessageInfoView, ApporveView {

    /**
     * 返回
     */
    @BindView(R.id.title_img_back)
    ImageView titleImgBack;
    /**
     * 返回
     */
    @BindView(R.id.title_layout_left)
    RelativeLayout titleLayoutLeft;
    /**
     * 标题
     */
    @BindView(R.id.title_topbar)
    TextView titleTopbar;
    /**
     * 姓名
     */
    @BindView(R.id.username)
    EditText username;
    /**
     * 性别
     */
    @BindView(R.id.sex)
    EditText sex;
    /**
     * 身份证号
     */
    @BindView(R.id.idcard)
    EditText idcard;
    /**
     * 确认按钮
     */
    @BindView(R.id.ok_buton)
    Button okButon;
    /**
     * 重新扫描
     */
    @BindView(R.id.agin_scain)
    TextView aginScain;
    /**
     * 头像
     */
    @BindView(R.id.user_image)
    MyImageView userImage;
    /**
     * title布局
     */
    @BindView(R.id.basetitle_bar)
    RelativeLayout basetitleBar;
    /**
     * 编辑
     */
    @BindView(R.id.home_tv_num)
    TextView home_tv_num;
    /**
     * 编辑布局
     */
    @BindView(R.id.right_layout)
    RelativeLayout right_layout;


    SubcomitPresenter pres;
    SetPresenter setPresenter;
    TeamPresenter teamPresenters;

    CustomBackDialog customBackDialog;
    private int isOk = 0;

    int renzheng = 0;
    String keyname = "";
    String uptoken = "";
    boolean uptokens = true;
    String token = "";


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_submit);
        ButterKnife.bind(this);
        basetitleBar.setBackgroundColor(Color.parseColor(SystemConfigFactory.getInstance(SubmitActivity.this).getSystemConfig().getColor()));
        token = SystemConfigFactory.getInstance(SubmitActivity.this).getSystemConfig().getToken();
        initView();
        upload_img();
        CommonUtils.url_code = 1;
        upload_ocimg();
        //先获取七牛token
        setPresenter.getUploadToken();
    }

    @Override
    protected BasePresenter createPresenter() {
        return null;
    }

    /**
     * 初始化数据
     */
    public void initView() {
        TintManager.setTint(okButon, Color.parseColor(SystemConfigFactory.getInstance(this).getSystemConfig().getColor()));

        pres = new SubcomitPresenter(SubmitActivity.this);
        setPresenter = new SetPresenter(this);
        teamPresenters = new TeamPresenter((MessageInfoView) this);

        titleImgBack.setImageResource(R.mipmap.fanhui);
        home_tv_num.setText(getString(R.string.bianji));
        home_tv_num.setVisibility(View.VISIBLE);
        titleTopbar.setText(getString(R.string.saomiao));

        username.setEnabled(false);
        sex.setEnabled(false);
        idcard.setEnabled(false);

        //重置是否是第一次进入程序
        CommonUtils.isFirst = true;
        CommonUtils.idcard = 0;
    }


    @OnClick({R.id.title_layout_left, R.id.ok_buton, R.id.agin_scain, R.id.right_layout})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.title_layout_left://返回
                Intent intents = new Intent(this, CaptureActivity.class);
                intents.putExtra("isIdcard", 1);
                startActivity(intents);
                finish();
                break;
            case R.id.ok_buton://确认按钮
                if (renzheng == 1) {
                    String token = SystemConfigFactory.getInstance(SubmitActivity.this).getSystemConfig().getToken();
                    String name = username.getText().toString().trim();
                    String sexs = sex.getText().toString().trim();
                    String img = SystemConfigFactory.getInstance(SubmitActivity.this).getSystemConfig().getUserimgName();
                    String idcardimg = SystemConfigFactory.getInstance(SubmitActivity.this).getSystemConfig().getImageNmae();
                    String idcardnumber = idcard.getText().toString().trim();

                    if (name == null || ("").equals(name)) {
                        Toast.makeText(SubmitActivity.this, "请重新认证！", Toast.LENGTH_SHORT).show();
                        break;
                    } else if (sexs == null || "".equals(sexs)) {
                        Toast.makeText(SubmitActivity.this, "请重新认证！", Toast.LENGTH_SHORT).show();
                        break;
                    } else if (idcardnumber == null || "".equals(idcardnumber)) {
                        Toast.makeText(SubmitActivity.this, "请重新认证！", Toast.LENGTH_SHORT).show();
                        break;
                    }
                    CommonUtils.url_code = 0;
                    pres.upload(name, sexs, idcardnumber, img, idcardimg, token);
                    showLoading();
                } else if (renzheng == 2) {
                    Toast.makeText(SubmitActivity.this, "请先认证！", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.agin_scain://重新扫描
                Intent intent = new Intent(this, CaptureActivity.class);
                intent.putExtra("isIdcard", 1);
                startActivity(intent);
                finish();
                break;
            case R.id.right_layout://编辑
                if (isOk == 0) {//编辑
                    back_dialog();
                    isOk = 1;
                } else {//完成
                    isOk = 0;
                    home_tv_num.setText(getString(R.string.bianji));
                    username.setEnabled(false);
                    sex.setEnabled(false);
                    idcard.setEnabled(false);
                }
                break;
        }
    }

    /**
     * 提示弹框
     */
    public void back_dialog() {
        customBackDialog = new CustomBackDialog(SubmitActivity.this);
        customBackDialog.setOnPositiveListener(new View.OnClickListener() {//取消

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                customBackDialog.dismiss();
            }
        });
        customBackDialog.setOnNegativeListener(new View.OnClickListener() {//确认
            @Override
            public void onClick(View v) {
                home_tv_num.setText(getString(R.string.oks));
                username.setEnabled(true);
                username.setSelection(username.getText().toString().length());
                sex.setEnabled(true);
                sex.setSelection(sex.getText().toString().length());
                idcard.setEnabled(true);
                idcard.setSelection(idcard.getText().toString().length());
                customBackDialog.dismiss();
            }
        });
        customBackDialog.show();
    }

    /**
     * 上传到本地服务器
     */
    public void upload_img() {
        CommonUtils.url_code = 0;
        Log.e("mwh", "CommonUtils.idcard_file" + CommonUtils.idcard_file);
        pres.approveidcard(token, "messenger_01.png", CommonUtils.idcard_file);
        showLoading();
    }

    /**
     * 上传到认证平台
     */
    public void upload_ocimg() {
        ToastUtil.e("mwh", "上传认证平台");
        CommonUtils.url_code = 1;
        Map<String, String> map = new HashMap<>();
        map.put("key", "PeDcDeVPLrhk3NhimAYXZg");
        map.put("secret", "07c76c42f8204052809c74893bd3c21a");
        map.put("typeId", "2");
        map.put("format", "json");
        pres.ocidcard(map, CommonUtils.idcard_file);
    }

    @Override
    public void approveid(IdBean result) {
        MessageBean message = result.getMessage();

        int status = message.getStatus();
        ToastUtil.e("mwh", "status" + status);
        ToastUtil.e("mwh", "message.getValue" + message.getValue());
        if (status < 0) {
            dismissLoading();
            renzheng = 2;
            Toast.makeText(SubmitActivity.this, "认证失败，请重新选择", Toast.LENGTH_SHORT).show();
        } else {
            CommonUtils.url_code = 0;
            dismissLoading();
            ToastUtil.e("mwh", "上传认证平台成功");
            List<CardInfoBean> cardsinfo = result.getCardsinfo();
            CardInfoBean cardInfoBean = cardsinfo.get(0);
            List<ItemBean> items = cardInfoBean.getItems();
            ItemBean nameitem = items.get(1);
            String name = nameitem.getContent();
            ItemBean sexitem = items.get(2);
            String sexs = sexitem.getContent();
            ItemBean idnumberitem = items.get(6);
            String idnumber = idnumberitem.getContent();
            ItemBean contentitem = items.get(7);
            //图片Base64
            String content = contentitem.getContent();
            String strFile = "";
            try {
                byte[] decode = Base64.decode(content, Base64.DEFAULT);
                Bitmap bitmap = BitmapFactory.decodeByteArray(decode, 0, decode.length);
                strFile = ChuliPhoto.saveBitmaps(SubmitActivity.this, bitmap, "heads");
                userImage.setImageBitmap(BitmapFactory.decodeFile(strFile));
            } catch (Exception e) {
                e.printStackTrace();
            } finally {

            }

            SystemConfigFactory.getInstance(SubmitActivity.this).getSystemConfig().setUsername(name);
            SystemConfigFactory.getInstance(SubmitActivity.this).getSystemConfig().setUsersex(sexs);
            SystemConfigFactory.getInstance(SubmitActivity.this).getSystemConfig().setUseridcard(idnumber);

            username.setText(SystemConfigFactory.getInstance(SubmitActivity.this).getSystemConfig().getUsername());
            sex.setText(SystemConfigFactory.getInstance(SubmitActivity.this).getSystemConfig().getUsesex());
            idcard.setText(SystemConfigFactory.getInstance(SubmitActivity.this).getSystemConfig().getUseridcard());

            ToastUtil.e("mwh", "上传头像");
            if (uptoken != null) {
                uploadImageToQiniu(strFile, uptoken);
                renzheng = 1;
                showLoading();
            } else {
                uptokens = false;
                CommonUtils.url_code = 1;
                setPresenter.getUploadToken();
            }
        }
    }

    @Override
    public void approvecard(IdCardBean result) {
        //上传到本地服务器成功
        String imageName = result.getImageName();
        ToastUtil.e("mwh", "imageName" + imageName);
        SystemConfigFactory.getInstance(SubmitActivity.this).getSystemConfig().setImageName(imageName);
    }

    @Override
    public void uoloadmessage(ComitMessageBean result) {
        dismissLoading();
        SystemConfigFactory.getInstance(SubmitActivity.this).getSystemConfig().setStatus(result.getStatus());
        SystemConfigFactory.getInstance(SubmitActivity.this).getSystemConfig().setToken(result.getAppToken());
        Intent intent = new Intent(SubmitActivity.this, MainActivity.class);
        intent.putExtra("intent", 0);
        startActivity(intent);
        finish();
    }

    /**
     * 上传图片到七牛
     *
     * @param filePath 要上传的图片路径
     * @param token    在七牛官网上注册的token
     */
    private void uploadImageToQiniu(final String filePath, String token) {
        UploadManager uploadManager = new UploadManager();
        // 设置图片名字
        int v = (int) (Math.random() * (9999 - 1000 + 1)) + 1000;//产生1000-9999的随机数;
        try {
            final String mtime = makeTime.mtime();
            keyname = v + mtime;
        } catch (Exception e) {
            e.printStackTrace();
            dismissLoading();
        }
        uploadManager.put(filePath, keyname, token, new UpCompletionHandler() {
            @Override
            public void complete(String key, ResponseInfo info, JSONObject res) {

                // info.error中包含了错误信息，可打印调试
                // 上传成功后将key值上传到自己的服务器
                if (info.isOK()) {
                    dismissLoading();
                    CommonUtils.url_code = 0;
//                    teamPresenters.upLoadImage(SystemConfigFactory.getInstance(SubmitActivity.this).getSystemConfig().getToken(), keyname);
                    SystemConfigFactory.getInstance(SubmitActivity.this).getSystemConfig().
                            setUserimg(filePath);
                    SystemConfigFactory.getInstance(SubmitActivity.this).getSystemConfig().setUserimgName(keyname);
                } else {
                    dismissLoading();
                    //如果失败，这里可以把info信息上报自己的服务器，便于后面分析上传错误原因
                    //ToastUtil.show(SubmitActivity.this, "上传失败");
                }
            }
        }, null);
    }

    /**
     * 获取七牛token
     *
     * @param tokenBean
     */
    @Override
    public void getUploadToken(TokenBean tokenBean) {
        uptoken = tokenBean.getUptoken();
        if (!uptokens && !"".equals(uptoken)) {
            String filepath = SystemConfigFactory.getInstance(SubmitActivity.this).getSystemConfig().getUserimg();
            uploadImageToQiniu(filepath, uptoken);
        }
    }

    @Override
    public void subMitFeed(FeedBackBean feedBackBean) {

    }

    /**
     * 上传本地服务器头像名字
     *
     * @param result
     */
    @Override
    public void checkUpImage(String result) {

    }

    @Override
    public void erroy() {
        renzheng = 1;
        dismissLoading();
        Toast.makeText(SubmitActivity.this, getString(R.string.erry), Toast.LENGTH_SHORT).show();
    }

    @Override
    public void erry(String result) {
        renzheng = 1;
        dismissLoading();
        Toast.makeText(SubmitActivity.this, result, Toast.LENGTH_SHORT).show();
        if (result.contains("过期")) {
            getSharedPreferences("appbase", Context.MODE_PRIVATE).edit().clear().commit();
            SystemConfigFactory.getInstance(SubmitActivity.this).getSystemConfig().SetLogin(false);
            SystemConfigFactory.getInstance(SubmitActivity.this).getSystemConfig().setIsFirst(true);
            Intent intent = new Intent(SubmitActivity.this, LoginActivity.class);
            startActivity(intent);
            finish();
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            Intent intent = new Intent(this, CaptureActivity.class);
            intent.putExtra("isIdcard", 1);
            startActivity(intent);
            finish();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

}
